//
//  MapViewController.m
//  ChatKit-OC
//
//  Created by th on 2017/3/17.
//  Copyright © 2017年 ElonChan. All rights reserved.
//

#import "MapViewController.h"
#import "AVUser.h"
#import "LCChatKit.h"
#import "LCCKExampleConstants.h"

#import <MAMapKit/MAMapKit.h>

#import <AMapFoundationKit/AMapFoundationKit.h>

#import <AMapSearchKit/AMapSearchKit.h>

#import <MapKit/MapKit.h>

//#import <AMapNaviKit/AMapNaviKit.h>

#import "UIAutoScrollView.h"
#import "SelectPlaceTableViewController.h"
#import "MANaviRoute.h"
#import "RoutePlanDriveViewController.h"
#import "CommonUtility.h"
#import "DriveNaviViewController.h"
#import "WalkNaviViewController.h"
#import "RideNaviViewController.h"

@interface MapViewController ()<MAMapViewDelegate, AMapSearchDelegate, UITextFieldDelegate, SelectPlaceDelegate> {
    BOOL _hasCurrLoc;
}

@property (nonatomic, copy) NSString *pName;

@property (nonatomic, copy) NSString *cName;

//地图
@property (nonatomic, strong) MAMapView *mapView;

//地理编码
@property (strong,nonatomic) CLGeocoder *geocoder;

//子账号大头针
@property (nonatomic, strong) MAPointAnnotation *childAnnotation;

//搜索结果大头针
@property (nonatomic, strong) MAPointAnnotation *searchAnnotation;

@property (nonatomic, copy) NSString *currentCity;

//圆
@property (nonatomic, strong) MACircle *circle;

/** 是否在圆圈内 */
@property (nonatomic, assign) BOOL isContains;

/** 搜索到的位置 */
@property (nonatomic)  CLLocationCoordinate2D s_Center;

/** 子账号的位置 */
//@property (nonatomic) CLLocationCoordinate2D c_location;

@property (nonatomic) CLLocationCoordinate2D oldCenter;

/** 半径 */
@property (nonatomic, assign) CGFloat radius;

@property (nonatomic, strong) AMapRoute *route;

/* 用于显示当前路线方案. */
@property (nonatomic, strong) MANaviRoute *naviRoute;
/* 当前路线方案索引值. */
@property (nonatomic) NSInteger currentCourse;


/** 是否可以导航到搜索的地点，如果有子账号了就不行 */
@property (nonatomic, assign) BOOL isSearchNavi;


@property (nonatomic, copy) NSString *currentPlace;

@property (nonatomic, strong) AMapSearchAPI *search;
//父账号监控定时器
@property (nonatomic, strong)  NSTimer *pTimer;

//子位置更新定时器
@property (nonatomic, strong)  NSTimer *cTimer;

@property (nonatomic, strong) UIAutoScrollView *keyScrollView;

@property (nonatomic, strong) UIView *tfView;

@property (nonatomic, strong) UITextField *placeTF;

@property (nonatomic, strong) UITextField *radiusTF;

@property (nonatomic, strong) UIButton *tfButton;

@property (nonatomic, strong) UIButton *childLocationBtn;

@property (nonatomic, strong) UIButton *backBtn;

@property (nonatomic, strong) UIButton *navBtn;

@end

@implementation MapViewController

- (AMapSearchAPI *)search {
    if (!_search) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return _search;
}

-(CLGeocoder *)geocoder{
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc]init];
    }
    return _geocoder;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    [self setStatusBarBackgroundColor:[UIColor colorWithRed:0.11 green:0.48 blue:0.90 alpha:1.00]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO];
    
    //为了不影响其他页面在viewDidDisappear做以下设置
    self.navigationController.navigationBar.translucent = YES;//透明
    [self setStatusBarBackgroundColor:[UIColor clearColor]];
    
}

#pragma mark - 设置状态栏颜色，这里没用到这个方法
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    //设置状态栏颜色，然后在info.plist 修改View controller-based status bar appearance 为NO
    [UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleLightContent;
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

- (void)invalidateTimer:(NSNotification *)sender {
    [self deleteTimer];
}
- (void)deleteTimer {
    [_pTimer invalidate];
    [_cTimer invalidate];
    
    _pTimer = nil;
    _cTimer = nil;
}

- (void)removeBindWithChild:(NSNotification *)sender {
    
    [self deleteTimer];
    _navBtn.hidden = YES;
    _cName = nil;
    
    if (_mapView && _childAnnotation) {
        [_mapView removeAnnotation:_childAnnotation];
        _childAnnotation = nil;
        
        [self clearRoute];
    }
}

- (void)bindWithChild:(NSNotification *)sender {
    
    [self deleteTimer];
    _navBtn.hidden = YES;
    _cName = nil;
    
    _isSearchNavi = NO;
    
    if (_mapView && _searchAnnotation && _circle) {
        [_mapView removeAnnotation:_searchAnnotation];
        _childAnnotation = nil;
        
        [_mapView removeOverlay:_circle];
        _circle = nil;
        
        [self clearRoute];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"地图";
    
    [self initMapView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(invalidateTimer:) name:kInvalidateTimer object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeBindWithChild:) name:kRemoveBindingWithNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bindWithChild:) name:kBindingWithNotification object:nil];
}

#pragma mark - 初始化地图界面
- (void)initMapView
{
    _keyScrollView = [[UIAutoScrollView alloc] initWithFrame:CGRectMake(0, 0, kMainWidth, kMainHeight - STATUS_BAR_HEIGHT)];
    
    [_mapView clearDisk];
    
    _mapView = [[MAMapView alloc]initWithFrame:_keyScrollView.bounds];
    
    _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    _mapView.delegate = self;
    
    _mapView.mapType = MAMapTypeBus;
    
    _mapView.allowsBackgroundLocationUpdates = YES;//后台
    
    [_keyScrollView addSubview:_mapView];
    
    [self.view addSubview:_keyScrollView];
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    //当前定位
    _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, _mapView.maxY_pro - 40 - 35 - kSpaceX, 33, 33)];
    
    _backBtn.backgroundColor = [UIColor colorWithRed:1.00 green:1.00 blue:1.00 alpha:1.00];
    
    _backBtn.layer.borderWidth = 1;
    
    _backBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    _backBtn.layer.cornerRadius = 5;
    
    [_backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    
    [_backBtn addTarget:self action:@selector(backLocation) forControlEvents:UIControlEventTouchUpInside];
    
    [_mapView addSubview:_backBtn];
    
    //子账号定位
    _childLocationBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, _backBtn.y_pro - 35 - kSpaceX, 35, 35)];
    
    [_childLocationBtn setImage:[UIImage imageNamed:@"btn_map_locate"] forState:UIControlStateNormal];
    
    [_childLocationBtn addTarget:self action:@selector(locationWithChild) forControlEvents:UIControlEventTouchUpInside];
    
    [_mapView addSubview:_childLocationBtn];
    
    //导航按钮
    _navBtn = [[UIButton alloc] initWithFrame:CGRectMake(_childLocationBtn.maxX_pro + kSpaceX, _childLocationBtn.y_pro, 35, 35)];
    
    [_navBtn setTitle:@"导航" forState:UIControlStateNormal];
    
    _navBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    [_navBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    _navBtn.backgroundColor = [UIColor colorWithRed:0.27 green:0.48 blue:1.00 alpha:1.00];
    
    _navBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    _navBtn.layer.cornerRadius = 35*0.5;
    
    //    [_navBtn sizeToFit];
    
    [_mapView addSubview:_navBtn];
    
    [_navBtn addTarget:self action:@selector(naviAction) forControlEvents:UIControlEventTouchDown];
    
    _navBtn.hidden = YES;
    
    
    //减号
    UIButton *decBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, _childLocationBtn.y_pro - 35 - kSpaceX, 35, 35)];
    [decBtn setImage:[UIImage imageNamed:@"decrease"] forState:UIControlStateNormal];
    
    [decBtn addTarget:self action:@selector(zoomMinusAction) forControlEvents:UIControlEventTouchUpInside];
    
    //加号
    UIButton *incBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, decBtn.y_pro - 35 - kSpaceX, 35, 35)];
    [incBtn setImage:[UIImage imageNamed:@"increase"] forState:UIControlStateNormal];
    
    [incBtn addTarget:self action:@selector(zoomPlusAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_mapView addSubview:incBtn];
    [_mapView addSubview:decBtn];
    
    
    //显示或隐藏
    _tfButton = [[UIButton alloc] initWithFrame:CGRectMake(_mapView.width_pro - 35, fabs((_backBtn.maxY_pro - _childLocationBtn.y_pro - 30) * 0.5) + _childLocationBtn.y_pro, 35, 35)];
    
    _tfButton.backgroundColor = [UIColor whiteColor];
    
    _tfButton.layer.borderWidth = 1;
    
    _tfButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    _tfButton.layer.cornerRadius = 5;
    
    [_tfButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    
    [_tfButton addTarget:self action:@selector(showTFView) forControlEvents:UIControlEventTouchUpInside];
    
    [_mapView addSubview:_tfButton];
    
    //设置输入view
    
    _tfView = [[UIView alloc] initWithFrame:CGRectMake(_mapView.width_pro, _childLocationBtn.y_pro, kMainWidth - _childLocationBtn.maxX_pro - kSpaceX, _backBtn.maxY_pro - _childLocationBtn.y_pro)];
//    _tfView = [[UIView alloc] initWithFrame:CGRectMake(_childLocationBtn.maxX_pro + kSpaceX, _childLocationBtn.y_pro, kMainWidth - _childLocationBtn.maxX_pro - kSpaceX, _backBtn.maxY_pro - _childLocationBtn.y_pro)];
    
    _tfView.backgroundColor = [UIColor whiteColor];
    
    _tfView.layer.cornerRadius = 6;
    
    _tfView.layer.borderWidth = 1;
    
    _tfView.layer.borderColor = [UIColor grayColor].CGColor;
    
    [_mapView addSubview:_tfView];
    
    //确认按钮
    UIButton *checkBtn = [[UIButton alloc] initWithFrame:CGRectMake(_tfView.width_pro - 50, 0, 50, _tfView.height_pro)];
    
    [checkBtn setTitle:@"确定" forState:UIControlStateNormal];
    
    [checkBtn addTarget:self action:@selector(searchPlace) forControlEvents:UIControlEventTouchUpInside];
    
    checkBtn.backgroundColor = [UIColor colorWithRed:0.27 green:0.48 blue:1.00 alpha:1.00];
    
    [_tfView addSubview:checkBtn];
    
    //输入地名
    _placeTF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, _tfView.width_pro - checkBtn.width_pro, _tfView.height_pro * 0.5)];
    _placeTF.font = [UIFont systemFontOfSize:14];
    _placeTF.textAlignment = NSTextAlignmentCenter;
    _placeTF.placeholder = @"请输入地点";
    
    _placeTF.delegate = self;
    
    _placeTF.returnKeyType = UIReturnKeyNext;
    
    [_tfView addSubview:_placeTF];
    
    [_placeTF addLineViewPositionType:kBottom_Type];
    
    
    //输入半径
    _radiusTF = [[UITextField alloc] initWithFrame:CGRectMake(0, _placeTF.maxY_pro + 1, _tfView.width_pro - checkBtn.width_pro, _tfView.height_pro * 0.5 - 1)];
    _radiusTF.font = [UIFont systemFontOfSize:14];
    _radiusTF.textAlignment = NSTextAlignmentCenter;
    _radiusTF.placeholder = @"请输入范围";
    
    _radiusTF.delegate = self;
    
    _radiusTF.keyboardType = UIKeyboardTypeASCIICapableNumberPad;
    _radiusTF.returnKeyType = UIReturnKeyDone;
    
    [_tfView addSubview:_radiusTF];
    
    [_keyScrollView addAutoScrollAbility];
}
- (void)zoomPlusAction
{
    CGFloat oldZoom = self.mapView.zoomLevel;
    [self.mapView setZoomLevel:(oldZoom + 1) animated:YES];
    self.mapView.showsScale = YES;
}

- (void)zoomMinusAction
{
    CGFloat oldZoom = self.mapView.zoomLevel;
    [self.mapView setZoomLevel:(oldZoom - 1) animated:YES];
    self.mapView.showsScale = NO;
}

#pragma textFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if (textField == _placeTF) {
        [_placeTF resignFirstResponder];
        [_radiusTF becomeFirstResponder];
        
    } else if (textField == _radiusTF){
        [self searchPlace];
    }
    return NO;
}

#pragma mark - 搜索
- (void)searchPlace {
    
    if (_placeTF.text.length == 0) {
        [self showMsg:@"请输入地点" type:LCCKMessageNotificationTypeError];
    } else if (_radiusTF.text.length == 0) {
        [self showMsg:@"请输入范围" type:LCCKMessageNotificationTypeError];
    } else {
        
        AMapGeocodeSearchRequest *geo = [[AMapGeocodeSearchRequest alloc] init];
        geo.address = _placeTF.text;
        geo.city = _currentCity;
        [self.search AMapGeocodeSearch:geo];
        
        [self hideTFView];
        
        NSMutableArray *locations = [NSMutableArray array];
        
        [self.geocoder geocodeAddressString:_placeTF.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
           
            [placemarks enumerateObjectsUsingBlock:^(CLPlacemark * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [locations addObject:obj];
                
            }];
            
            SelectPlaceTableViewController *vc = [SelectPlaceTableViewController new];
            
            vc.datas = locations;
            vc.delegate = self;
            
            [self.navigationController pushViewController:vc animated:YES];
            
        }];
    }
}
#pragma mark - 逆地理编码回调.取得当前城市
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil){
        
//        [self showMsg:response.regeocode.addressComponent.city type:LCCKMessageNotificationTypeSuccess];
        
        _currentCity = response.regeocode.addressComponent.city;
        
    } else {
        [self showMsg:@"查询失败" type:LCCKMessageNotificationTypeError];
    }
}

#pragma mark - SelectPlaceDelegate
#warning SelectPlaceDelegate
- (void)SelectPlaceDelegateWithLocation:(CLLocation *)location placeName:(NSString *)placeName {
    MJWeakSelf;
    //搜索结果的位置
    CLLocationCoordinate2D s_Center = location.coordinate;
    
    self.s_Center = s_Center;
    
    _navBtn.hidden = NO;
    
    void(^initSearchAnnotation)() = ^(){
        
        weakSelf.isSearchNavi = YES;
        
        if (_cName.length > 0) {
            [_mapView removeAnnotation:_searchAnnotation];
        }
        
        _searchAnnotation = [MAPointAnnotation new];
        
//        _searchAnnotation.lockedToScreen = NO;
        
        [_mapView addAnnotation:_searchAnnotation];
        
        _searchAnnotation.title = placeName;
        
        _searchAnnotation.coordinate = s_Center;
        
        [_mapView setCenterCoordinate:s_Center animated:YES];
        
        //构造圆
        [_mapView removeOverlay:_circle];
        
        _circle = [MACircle circleWithCenterCoordinate:CLLocationCoordinate2DMake(s_Center.latitude, s_Center.longitude) radius:[_radiusTF.text floatValue]];
        
        //在地图上添加圆
        [_mapView addOverlay: _circle];
    };
    
    if (_cName.length > 0) {
        //当前账号是父账号
        
        AVQuery *query = [AVQuery queryWithClassName:kUser];
        
        [query whereKey:@"username" equalTo:_cName];//精确查询
        
        [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
            
            if (!error && objects.count > 0) {
                
                NSString *longitude = [objects[0] objectForKey:kLongitude];
                
                NSString *latitude = [objects[0] objectForKey:kLatitude];
                
                if (longitude.length > 0 && latitude.length > 0) {
                    
                    weakSelf.isSearchNavi = NO;
                    
                    [weakSelf initWithChildAnnotaion];
                    
                    //子账号位置
                    CLLocationCoordinate2D c_location = CLLocationCoordinate2DMake([latitude floatValue], [longitude floatValue]);
                    
                    weakSelf.childAnnotation.coordinate = c_location;
                    
                    [weakSelf.mapView setCenterCoordinate:s_Center animated:YES];
                    
                    //构造圆
                    [weakSelf.mapView removeOverlay:_circle];
                    
                    weakSelf.circle = [MACircle circleWithCenterCoordinate:CLLocationCoordinate2DMake(s_Center.latitude, s_Center.longitude) radius:[_radiusTF.text floatValue]];
                    
                    //在地图上添加圆
                    [weakSelf.mapView addOverlay: weakSelf.circle];
                    
                    //判断一个点是否在圆内，类似于地理围栏功能，返回YES，表示进入围栏，返回NO，表示离开围栏。
                    BOOL isContains = MACircleContainsCoordinate(c_location, s_Center, [weakSelf.radiusTF.text floatValue]);
                    
                    if (isContains) {
                        //如果在圆圈内
                        
                        [weakSelf showMsg:NSStringFormat(@"开始监测 %@ 是否当前范围内",weakSelf.cName) type:LCCKMessageNotificationTypeSuccess];
                        
                        weakSelf.isContains = YES;
                        
                        weakSelf.radius = [weakSelf.radiusTF.text floatValue];
                        
                        weakSelf.currentPlace = placeName;
                        
                    } else {
                        weakSelf.isContains = NO;
                        [weakSelf showMsg:NSStringFormat(@"%@ 不在当前范围内",weakSelf.cName) type:LCCKMessageNotificationTypeError];
                    }
                    
                } else {
                    initSearchAnnotation();
                    [weakSelf showMsg:@"子账号还没有位置记录" type:LCCKMessageNotificationTypeError];
                }
            } else {
                initSearchAnnotation();
                [weakSelf showMsg:@"子账号还没有位置记录" type:LCCKMessageNotificationTypeError];
            }
        }];
//        [self getChildLocationWithName:cName];
        
    } else {
        initSearchAnnotation();
    }
    
    
}
////////////////////////////////////////////////////
#pragma mark - 路径规划搜索回调
/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response {
    if (response.route == nil) {
        return;
    }
    
    if (response.count > 0) {
        
        [self clearRoute];
        
        self.route = response.route;
        
        if ([request isKindOfClass:[AMapDrivingRouteSearchRequest class]]) {
            
            MANaviAnnotationType type = MANaviAnnotationTypeDrive;
            
            if (self.isSearchNavi) {
                //规划搜索到的地点
                self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.s_Center.latitude longitude:self.s_Center.longitude]];
                
            } else {
                //规划到子账号的位置
                
                self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.childAnnotation.coordinate.latitude longitude:self.childAnnotation.coordinate.longitude]];
            }
            
            [self.naviRoute addToMapView:self.mapView];
            
            /* 缩放地图使其适应polylines的展示. */
            [self.mapView showOverlays:self.naviRoute.routePolylines edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge) animated:YES];
            
        } else if ([request isKindOfClass:[AMapTransitRouteSearchRequest class]]) {
            
            if (self.isSearchNavi) {
                //规划搜索到的地点
            self.naviRoute = [MANaviRoute naviRouteForTransit:self.route.transits[self.currentCourse] startPoint:[AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.s_Center.latitude longitude:self.s_Center.longitude]];
                
            } else {
                //规划到子账号的位置
                
                self.naviRoute = [MANaviRoute naviRouteForTransit:self.route.transits[self.currentCourse] startPoint:[AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.childAnnotation.coordinate.latitude longitude:self.childAnnotation.coordinate.longitude]];
            }
            
            [self.naviRoute addToMapView:self.mapView];
            
            /* 缩放地图使其适应polylines的展示. */
            [self.mapView showOverlays:self.naviRoute.routePolylines edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge) animated:YES];
            
        } else if ([request isKindOfClass:[AMapWalkingRouteSearchRequest class]]){
            
            MANaviAnnotationType type = MANaviAnnotationTypeWalking;
            
            if (self.isSearchNavi) {
                //规划搜索到的地点
                self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.s_Center.latitude longitude:self.s_Center.longitude]];
                
            } else {
                //规划到子账号的位置
                self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.childAnnotation.coordinate.latitude longitude:self.childAnnotation.coordinate.longitude]];
            }
            [self.naviRoute addToMapView:self.mapView];
            
            /* 缩放地图使其适应polylines的展示. */
            [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines]
                                edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge)
                                   animated:YES];
        } else if ([request isKindOfClass:[AMapRidingRouteSearchRequest class]]) {
            
            MANaviAnnotationType type = MANaviAnnotationTypeRiding;
            
            if (self.isSearchNavi) {
                //规划搜索到的地点
                self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.s_Center.latitude longitude:self.s_Center.longitude]];
                
            } else {
                //规划到子账号的位置
                self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.childAnnotation.coordinate.latitude longitude:self.childAnnotation.coordinate.longitude]];
            }
            
            [self.naviRoute addToMapView:self.mapView];
            
            /* 缩放地图使其适应polylines的展示. */
            [self.mapView showOverlays:self.naviRoute.routePolylines edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge) animated:YES];
        }
        
    } else {
        [self showMsg:@"未能成功查找该路线" type:LCCKMessageNotificationTypeError];
    }
}

#pragma 清空地图上已有的路线
- (void)clearRoute {
    if (self.naviRoute) {
        [self.naviRoute removeFromMapView];
        self.naviRoute = nil;
    }
}

#pragma mark - 弹出路径规划消息框
- (void)alertDriver {
    
    MJWeakSelf;
    
    //驾车
    void(^carBlock)() = ^(){
        
        AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
        
        navi.requireExtension = YES;
        navi.strategy = 5;
        
        /* 出发点. */
        navi.origin = [AMapGeoPoint locationWithLatitude:_mapView.userLocation.coordinate.latitude
                                               longitude:_mapView.userLocation.coordinate.longitude];
        
        if (weakSelf.isSearchNavi) {
            //规划搜索到的地点
            
            /* 目的地. */
            navi.destination = [AMapGeoPoint locationWithLatitude:self.s_Center.latitude
                                                        longitude:self.s_Center.longitude];
            
        } else {
            //规划到子账号的位置
            /* 目的地. */
            navi.destination = [AMapGeoPoint locationWithLatitude:self.childAnnotation.coordinate.latitude
                                                        longitude:self.childAnnotation.coordinate.longitude];
        }
        
        [self.search AMapDrivingRouteSearch:navi];
    };
    
    //公交
    void(^busBlock)() = ^(){
        
        AMapTransitRouteSearchRequest *navi = [[AMapTransitRouteSearchRequest alloc] init];
        
        navi.requireExtension = YES;
        
        if (weakSelf.currentCity.length == 0) {
            [weakSelf showMsg:@"暂未定位当前城市，请重新稍等" type:LCCKMessageNotificationTypeError];
            return;
        } else {
            navi.city = weakSelf.currentCity;
        }
        
        /* 出发点. */
        navi.origin = [AMapGeoPoint locationWithLatitude:_mapView.userLocation.coordinate.latitude
                                               longitude:_mapView.userLocation.coordinate.longitude];
        if (weakSelf.isSearchNavi) {
            //规划搜索到的地点
            
            /* 目的地. */
            navi.destination = [AMapGeoPoint locationWithLatitude:self.s_Center.latitude
                                                        longitude:self.s_Center.longitude];
            
        } else {
            //规划到子账号的位置
            /* 目的地. */
            navi.destination = [AMapGeoPoint locationWithLatitude:self.childAnnotation.coordinate.latitude
                                                        longitude:self.childAnnotation.coordinate.longitude];
        }
        
        [self.search AMapTransitRouteSearch:navi];
    };
    
    //步行
    void(^walkBlock)() = ^(){
        
        AMapWalkingRouteSearchRequest *navi = [[AMapWalkingRouteSearchRequest alloc] init];
        
        /* 1个方案*/
        navi.multipath = 0;
        
        /* 出发点. */
        navi.origin = [AMapGeoPoint locationWithLatitude:_mapView.userLocation.coordinate.latitude
                                               longitude:_mapView.userLocation.coordinate.longitude];
        if (weakSelf.isSearchNavi) {
            //规划搜索到的地点
            
            /* 目的地. */
            navi.destination = [AMapGeoPoint locationWithLatitude:self.s_Center.latitude
                                                        longitude:self.s_Center.longitude];
            
        } else {
            //规划到子账号的位置
            /* 目的地. */
            navi.destination = [AMapGeoPoint locationWithLatitude:self.childAnnotation.coordinate.latitude
                                                        longitude:self.childAnnotation.coordinate.longitude];
        }
        
        [self.search AMapWalkingRouteSearch:navi];
    };
    
    //骑行
    void(^cyclingBlock)() = ^(){
        
        AMapRidingRouteSearchRequest *navi = [[AMapRidingRouteSearchRequest alloc] init];
        
        /* 出发点. */
        navi.origin = [AMapGeoPoint locationWithLatitude:_mapView.userLocation.coordinate.latitude
                                               longitude:_mapView.userLocation.coordinate.longitude];
        if (weakSelf.isSearchNavi) {
            //规划搜索到的地点
            
            /* 目的地. */
            navi.destination = [AMapGeoPoint locationWithLatitude:self.s_Center.latitude
                                                        longitude:self.s_Center.longitude];
            
        } else {
            //规划到子账号的位置
            /* 目的地. */
            navi.destination = [AMapGeoPoint locationWithLatitude:self.childAnnotation.coordinate.latitude
                                                        longitude:self.childAnnotation.coordinate.longitude];
        }
        
        [self.search AMapRidingRouteSearch:navi];
    };
    
    
    CKAlertViewController *alertVC = [CKAlertViewController alertControllerWithTitle:@"线路规划" message:nil ];
    
    CKAlertAction *car = [CKAlertAction actionWithTitle:@"驾车路线规划" handler:^(CKAlertAction *action) {
        
        
        carBlock();
    }];
    
    CKAlertAction *walk = [CKAlertAction actionWithTitle:@"公交路线规划" handler:^(CKAlertAction *action) {
        busBlock();
    }];
    
    CKAlertAction *bus = [CKAlertAction actionWithTitle:@"步行路线规划" handler:^(CKAlertAction *action) {
        walkBlock();
    }];
    CKAlertAction *cycling = [CKAlertAction actionWithTitle:@"骑行路线规划" handler:^(CKAlertAction *action) {
        cyclingBlock();
    }];
    
    CKAlertAction *cancle = [CKAlertAction actionWithTitle:@"取消" handler:^(CKAlertAction *action) {
        
    }];
    
    [alertVC addAction:car];
    [alertVC addAction:walk];
    [alertVC addAction:bus];
    [alertVC addAction:cycling];
    [alertVC addAction:cancle];
    
    [self presentViewController:alertVC animated:NO completion:nil];

}

#pragma mark - 定位到子账号
#warning 定位到子账号
- (void)locationWithChild {
    
    MJWeakSelf;
    
    if (_isSearchNavi) {
        _navBtn.hidden = NO;
    } else {
        _navBtn.hidden = YES;
    }
    [_mapView removeAnnotation:_searchAnnotation];
    _searchAnnotation = nil;
    
    [self clearRoute];
    
    AVUser *user = [AVUser currentUser];
    
    AVQuery *query = [AVQuery queryWithClassName:kRelationship];
    
    [query whereKey:kUsername equalTo:user.username];
    
    [LCCKUtil showProgress];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        
        if (!error) {
            
            if (objects.count > 0) {
                
                void(^queryParent)() = ^(){
                    
                    if (weakSelf.pName.length == 0) {
                        //绑定了父账号
                        NSString *pObjectId = [[objects[0] objectForKey:kParent] objectForKey:kobjectId];
                        
                        AVQuery *pQuery = [AVQuery queryWithClassName:kUser];
                        [pQuery whereKey:kobjectId equalTo:pObjectId];
                        
                        [pQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                            if (objects.count > 0) {
                                
                                //查到父账号的名字
                                weakSelf.pName = [objects[0] objectForKey:kUsername];
                                [LCCKUtil hideProgress];
                            } else {
                                [LCCKUtil hideProgress];
                                [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                            }
                        }];
                    }
                };
                void(^queryChildren)() = ^(){
                    //绑定了子账号
                    NSString *pObjectId = [[objects[0] objectForKey:kChildren] objectForKey:kobjectId];
                    
                    AVQuery *pQuery = [AVQuery queryWithClassName:kUser];
                    [pQuery whereKey:kobjectId equalTo:pObjectId];
                    
                    [pQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                        if (objects.count > 0) {
                            
                            //查到子账号的名字
                            weakSelf.cName = [objects[0] objectForKey:kUsername];
                            
                            //获取子账号的位置
                            [self getChildLocationWithName:weakSelf.cName];
                            [LCCKUtil hideProgress];
                        } else {
                            [LCCKUtil hideProgress];
                            [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                        }
                        
                    }];
                };
                
                
                if ([objects[0] objectForKey:kParent] && ![objects[0] objectForKey:kChildren]) {
                    
                    //只有父账号
                    if (weakSelf.isSearchNavi) {
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                            [weakSelf alertDriver];
                        });
                    } else {
                        [weakSelf showMsg:@"您还没有绑定子账号哦" type:LCCKMessageNotificationTypeError];
                    }
                    
                    queryParent();
                    
                } else if ([objects[0] objectForKey:kChildren] && ![objects[0] objectForKey:kParent]) {
                    //只有子账号
                    queryChildren();
                    
                } else if ([objects[0] objectForKey:kChildren] && [objects[0] objectForKey:kParent]) {
                    
                    //查到子账号和父账号的名字
                    queryParent();
                    queryChildren();
                    
                } else {
                    //未绑定任何账号
                    [LCCKUtil hideProgress];
                    if (weakSelf.isSearchNavi) {
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                            [weakSelf alertDriver];
                        });
                    } else {
                        [weakSelf showMsg:@"还没有绑定子账号，无法定位子账号位置" type:LCCKMessageNotificationTypeError];
                    }
                }
                
            } else {
                //未绑定任何账号
                [LCCKUtil hideProgress];
                if (weakSelf.isSearchNavi) {
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        [weakSelf alertDriver];
                    });
                    
                } else {
                    
                    [weakSelf showMsg:@"还没有绑定子账号，无法定位子账号位置" type:LCCKMessageNotificationTypeError];
                }
                
            }
            
        } else {
            [LCCKUtil hideProgress];
            [LCCKUtil showNotificationWithTitle:@"账号关系查询失败" subtitle:nil type:LCCKMessageNotificationTypeError];
        }
    }];
    
}

#pragma mark - 获取子账号的经纬度
- (void)getChildLocationWithName:(NSString *)name {
    
    //定时器
    if (!_pTimer) {
        _pTimer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(getChildLoaction:) userInfo:@{@"name":name} repeats:YES];
        
        [[NSRunLoop currentRunLoop] addTimer:_pTimer forMode:NSDefaultRunLoopMode];
    }
    
    AVQuery *query = [AVQuery queryWithClassName:kUser];
    
    [query whereKey:@"username" equalTo:name];//精确查询
    
    MJWeakSelf;
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        
        if (!error && objects.count > 0) {
            
            NSString *longitude = [objects[0] objectForKey:kLongitude];
            
            NSString *latitude = [objects[0] objectForKey:kLatitude];
            
            if (longitude.length > 0 && latitude.length > 0) {
                
                [weakSelf initWithChildAnnotaion];
                
                CLLocationCoordinate2D center = CLLocationCoordinate2DMake([latitude floatValue], [longitude floatValue]);
                
                weakSelf.childAnnotation.coordinate = center;
                
                [weakSelf.mapView setCenterCoordinate:center animated:YES];
                
                weakSelf.navBtn.hidden = NO;
                
//                [weakSelf showMsg:NSStringFormat(@"%@ 纬度%@ 经度%@",name ,latitude, longitude) type:LCCKMessageNotificationTypeSuccess];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [weakSelf alertDriver];
                });
            } else {
                
                if (weakSelf.isSearchNavi) {
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        [weakSelf alertDriver];
                    });
                } else {
                    [weakSelf showMsg:@"子账号还没有位置记录" type:LCCKMessageNotificationTypeError];
                }
            }
        } else {
            
            if (weakSelf.isSearchNavi) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [weakSelf alertDriver];
                });
            } else {
                [weakSelf showMsg:@"子账号还没有位置记录" type:LCCKMessageNotificationTypeError];
            }
        }
    }];
    
}

////////////////////////////////////////////////////
#pragma mark - 导航
- (void)naviAction {
    MJWeakSelf;
   //驾车
    void(^driveBlock)() = ^(){
        DriveNaviViewController *vc = [DriveNaviViewController new];
        vc.startPoint = [AMapNaviPoint locationWithLatitude:weakSelf.mapView.userLocation.coordinate.latitude longitude:weakSelf.mapView.userLocation.coordinate.longitude];
        
        if (weakSelf.isSearchNavi) {
            vc.endPoint   = [AMapNaviPoint locationWithLatitude:weakSelf.s_Center.latitude longitude:weakSelf.s_Center.longitude];
        } else {
            vc.endPoint   = [AMapNaviPoint locationWithLatitude:weakSelf.childAnnotation.coordinate.latitude longitude:weakSelf.childAnnotation.coordinate.longitude];
        }
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    //步行
    void(^walkBlock)() = ^(){
        WalkNaviViewController *vc = [WalkNaviViewController new];
        vc.startPoint = [AMapNaviPoint locationWithLatitude:weakSelf.mapView.userLocation.coordinate.latitude longitude:weakSelf.mapView.userLocation.coordinate.longitude];
        
        if (weakSelf.isSearchNavi) {
            vc.endPoint   = [AMapNaviPoint locationWithLatitude:weakSelf.s_Center.latitude longitude:weakSelf.s_Center.longitude];
        } else {
            vc.endPoint   = [AMapNaviPoint locationWithLatitude:weakSelf.childAnnotation.coordinate.latitude longitude:weakSelf.childAnnotation.coordinate.longitude];
        }
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    //骑行
    void(^cyclingBlock)() = ^(){
        RideNaviViewController *vc = [RideNaviViewController new];
        vc.startPoint = [AMapNaviPoint locationWithLatitude:weakSelf.mapView.userLocation.coordinate.latitude longitude:weakSelf.mapView.userLocation.coordinate.longitude];
        
        if (weakSelf.isSearchNavi) {
            vc.endPoint   = [AMapNaviPoint locationWithLatitude:weakSelf.s_Center.latitude longitude:weakSelf.s_Center.longitude];
        } else {
            vc.endPoint   = [AMapNaviPoint locationWithLatitude:weakSelf.childAnnotation.coordinate.latitude longitude:weakSelf.childAnnotation.coordinate.longitude];
        }
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    CKAlertViewController *alertVC = [CKAlertViewController alertControllerWithTitle:@"导航选择" message:nil ];
    
    CKAlertAction *car = [CKAlertAction actionWithTitle:@"驾车导航" handler:^(CKAlertAction *action) {
        
        driveBlock();
    }];
    
    CKAlertAction *walk = [CKAlertAction actionWithTitle:@"步行导航" handler:^(CKAlertAction *action) {
        walkBlock();
    }];
    CKAlertAction *cycling = [CKAlertAction actionWithTitle:@"骑行导航" handler:^(CKAlertAction *action) {
        cyclingBlock();
    }];
    
    CKAlertAction *cancle = [CKAlertAction actionWithTitle:@"取消" handler:^(CKAlertAction *action) {
        
    }];
    
    [alertVC addAction:car];
    [alertVC addAction:walk];
    [alertVC addAction:cycling];
    [alertVC addAction:cancle];
    
    [self presentViewController:alertVC animated:NO completion:nil];
}

#pragma mark - MAMapViewDelegate
#warning MAMapViewDelegate
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    
    CLLocationCoordinate2D center = userLocation.location.coordinate;
    
    if (!_hasCurrLoc) {
        _hasCurrLoc = YES;
        
        _oldCenter = center;
        
        [self backLocation];
        
        //更新我的位置信息
        _cTimer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(updateCurrentUserWithLocation:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_cTimer forMode:NSDefaultRunLoopMode];
    }
    
    if (self.currentCity.length == 0) {
        //逆地理编码查询当前城市
        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
        
        regeo.location                    = [AMapGeoPoint locationWithLatitude:center.latitude longitude:center.longitude];
        regeo.requireExtension            = YES;
        regeo.radius                      = 3000;
        
        [self.search AMapReGoecodeSearch:regeo];
    }
    
    BOOL isContains = MACircleContainsCoordinate(userLocation.coordinate, _oldCenter, 50);
    if (!isContains) {//不在在当前范围内
        
        _oldCenter = center;
        
        [self backLocation];
    }
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    
    if ([overlay isKindOfClass:[MACircle class]]) {
        MACircleRenderer *circleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];
        
        circleRenderer.lineWidth    = 0.1f;
        circleRenderer.strokeColor  = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:0.6];
        circleRenderer.fillColor    = [UIColor colorWithRed:1.0 green:0.8 blue:0.0 alpha:0.3];
        return circleRenderer;
    }
    
    if ([overlay isKindOfClass:[LineDashPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth   = 8;
//        polylineRenderer.lineDashPattern = @[@10, @15];
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MANaviPolyline class]])
    {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        polylineRenderer.lineWidth = 8;
        
        if (naviPolyline.type == MANaviAnnotationTypeWalking)
        {
            polylineRenderer.strokeColor = self.naviRoute.walkingColor;
        }
        else if (naviPolyline.type == MANaviAnnotationTypeRailway)
        {
            polylineRenderer.strokeColor = self.naviRoute.railwayColor;
        }
        else
        {
            polylineRenderer.strokeColor = self.naviRoute.routeColor;
        }
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MAMultiPolyline class]])
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 8;
        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        polylineRenderer.gradient = YES;
        
        return polylineRenderer;
    }
    
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[_childAnnotation class]] || [annotation isKindOfClass:[_searchAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }
        
        annotationView.canShowCallout               = YES;
        annotationView.animatesDrop                 = YES;
        annotationView.draggable                    = NO;
        
        if ([annotation isKindOfClass:[_searchAnnotation class]]) {
            
            [annotationView setPinColor:MAPinAnnotationColorGreen];
        } else {
            [annotationView setPinColor:MAPinAnnotationColorRed];
        }
        
        
        return annotationView;
    }
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *routePlanningCellIdentifier = @"RoutePlanningCellIdentifier";
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:routePlanningCellIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:routePlanningCellIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.image = nil;
        
        if ([annotation isKindOfClass:[MANaviAnnotation class]])
        {
            switch (((MANaviAnnotation*)annotation).type)
            {
                case MANaviAnnotationTypeRailway:
                    poiAnnotationView.image = [UIImage imageNamed:@"railway_station"];
                    break;
                    
                case MANaviAnnotationTypeBus:
                    poiAnnotationView.image = [UIImage imageNamed:@"bus"];
                    break;
                    
                case MANaviAnnotationTypeDrive:
                    poiAnnotationView.image = [UIImage imageNamed:@"car"];
                    break;
                    
                case MANaviAnnotationTypeWalking:
                    poiAnnotationView.image = [UIImage imageNamed:@"man"];
                    break;
                    
                default:
                    break;
            }
        }
        else
        {
            /* 起点. */
            if ([[annotation title] isEqualToString:(NSString*)RoutePlanningViewControllerStartTitle])
            {
                poiAnnotationView.image = [UIImage imageNamed:@"startPoint"];
            }
            /* 终点. */
            else if([[annotation title] isEqualToString:(NSString*)RoutePlanningViewControllerDestinationTitle])
            {
                poiAnnotationView.image = [UIImage imageNamed:@"endPoint"];
            }
            
        }
        
        return poiAnnotationView;
    }
    
    return nil;
}

/**
 * @brief 地图将要发生缩放时调用此接口
 * @param mapView       地图view
 * @param wasUserAction 标识是否是用户动作
 */
- (void)mapView:(MAMapView *)mapView mapWillZoomByUser:(BOOL)wasUserAction {
    [self hideTFView];
}

/**
 * @brief 单击地图回调，返回经纬度
 * @param mapView 地图View
 * @param coordinate 经纬度
 */
- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate {
    [self hideTFView];
}
/**
 *  地图移动结束后调用此接口
 *
 *  @param mapView       地图view
 *  @param wasUserAction 标识是否是用户动作
 */
- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction {
    
}


#pragma mark - 更新当前账号的位置信息
- (void)updateCurrentUserWithLocation:(NSTimer *)time {
    
    AVUser *currentUser = [AVUser currentUser];
    
    [currentUser setObject:NSStringFormat(@"%lf",_mapView.userLocation.coordinate.longitude) forKey:kLongitude];
    
    [currentUser setObject:NSStringFormat(@"%lf",_mapView.userLocation.coordinate.latitude) forKey:kLatitude];
    
    [currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            
//            [self showMsg:@"位置更新成功" type:LCCKMessageNotificationTypeSuccess];
        } else {
            [self showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
        }
    }];
}

#pragma mark - 监控子账号位置信息 大头针变化
#warning 监控子账号位置信息 大头针变化
- (void)getChildLoaction:(NSTimer *)time {
    
    [self initWithChildAnnotaion];
    
    AVQuery *query = [AVQuery queryWithClassName:kUser];
    
    [query whereKey:@"username" equalTo:[time userInfo][@"name"]];
    
    MJWeakSelf;
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        if (!error && objects.count > 0) {
            
            NSString *longitude = [objects[0] objectForKey:kLongitude];
            
            NSString *latitude = [objects[0] objectForKey:kLatitude];
            
            if (longitude.length > 0 && latitude.length > 0) {
                CLLocationCoordinate2D center = CLLocationCoordinate2DMake([latitude floatValue], [longitude floatValue]);
                
                weakSelf.childAnnotation.coordinate = center;
                
                
                if (weakSelf.isContains) {
                    
                    //在圆圈内
                    CLLocationCoordinate2D c_location = CLLocationCoordinate2DMake([latitude floatValue], [longitude floatValue]);
                    
                    //判断一个点是否在圆内，类似于地理围栏功能，返回YES，表示进入围栏，返回NO，表示离开围栏。
                    BOOL isContains = MACircleContainsCoordinate(c_location, weakSelf.s_Center, weakSelf.radius);
                    
                    //如果不在了
                    if (!isContains && weakSelf.cName.length > 0) {
                        weakSelf.isContains = NO;
                        
                        NSString *title = NSStringFormat(@"%@ 已经走出%@ %0.0lfm范围了",weakSelf.cName, weakSelf.currentPlace, weakSelf.radius);
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:kmonitoringWithNotification object:nil userInfo:@{@"title":title}];
                        
                        [LocalNotification notifiWithContent:title];
                    }
                }
            }
            
            
        } else {
            [weakSelf showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
        }
    }];
}

#pragma mark -初始化大头针
- (void)initWithChildAnnotaion {
    
    if (!_childAnnotation) {
        _childAnnotation = [MAPointAnnotation new];
        
//        _childAnnotation.lockedToScreen = NO;
        
        if (_cName.length > 0) {
            _childAnnotation.title = _cName;
        }
        
        [_mapView addAnnotation:_childAnnotation];
    }
}

#pragma mark - 显示tfView
- (void)showTFView {
    
    MJWeakSelf;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.tfView.frame = CGRectMake(weakSelf.childLocationBtn.maxX_pro + kSpaceX, weakSelf.childLocationBtn.y_pro, kMainWidth - weakSelf.childLocationBtn.maxX_pro - kSpaceX, weakSelf.backBtn.maxY_pro - weakSelf.childLocationBtn.y_pro);
    }];
}

#pragma mark - 隐藏tfView
- (void)hideTFView {
    
    MJWeakSelf;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.tfView.frame = CGRectMake(weakSelf.mapView.width_pro, weakSelf.childLocationBtn.y_pro, kMainWidth - weakSelf.childLocationBtn.maxX_pro - kSpaceX, weakSelf.backBtn.maxY_pro - weakSelf.childLocationBtn.y_pro);
    }];
    
    [self.view endEditing:YES];
    
    [_keyScrollView setContentOffset:CGPointMake(0,-20) animated:YES];
}

#pragma mark - 回到当前位置
- (void)backLocation {
    
//    [_mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    
    CLLocationCoordinate2D center = _mapView.userLocation.coordinate;
    
    [_mapView setCenterCoordinate:center animated:YES];
}

- (void)showMsg:(NSString *)msg type:(LCCKMessageNotificationType)type {
    [LCCKUtil showNotificationWithTitle:msg
                               subtitle:nil
                                   type:type];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
